package com.nehc.nettyserver.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * Netty服务器
 * 
 * @author NEHC
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NettyServer {

    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private final EventLoopGroup businessGroup;
    private final ChannelManager channelManager;
    private final MessageHandler messageHandler;
    
    @Value("${netty.server.port:8081}")
    private int port;
    
    @Value("${netty.server.websocket.path:/ws}")
    private String websocketPath;
    
    @Value("${netty.server.heartbeat.interval:30}")
    private int heartbeatInterval;
    
    private Channel serverChannel;

    /**
     * 启动Netty服务器
     */
    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        
                        // HTTP协议相关处理器
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new HttpObjectAggregator(65536));
                        
                        // WebSocket协议处理器
                        pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath, null, true));
                        
                        // 心跳检测处理器
                        pipeline.addLast(new IdleStateHandler(heartbeatInterval, 0, 0, TimeUnit.SECONDS));
                        
                        // 自定义处理器
                        pipeline.addLast(businessGroup, "heartbeatHandler", new HeartbeatHandler());
                        pipeline.addLast(businessGroup, "authHandler", new AuthHandler());
                        pipeline.addLast(businessGroup, "messageHandler", messageHandler);
                    }
                });
        
        ChannelFuture future = bootstrap.bind(port).sync();
        if (future.isSuccess()) {
            serverChannel = future.channel();
            log.info("Netty服务器启动成功，监听端口: {}", port);
        } else {
            log.error("Netty服务器启动失败: {}", future.cause().getMessage());
            throw new RuntimeException("Netty服务器启动失败", future.cause());
        }
    }

    /**
     * 关闭Netty服务器
     */
    @PreDestroy
    public void stop() {
        log.info("关闭Netty服务器...");
        if (serverChannel != null) {
            serverChannel.close();
        }
        
        // 优雅关闭
        businessGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        
        // 断开所有连接
        channelManager.disconnectAll("服务器关闭");
        log.info("Netty服务器已关闭");
    }
} 